package adminorg;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TreeMap;

import com.vaadin.data.Property;
import com.vaadin.data.Property.ValueChangeEvent;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.Button;
import com.vaadin.ui.ComboBox;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.HorizontalSplitPanel;
import com.vaadin.ui.Label;
import com.vaadin.ui.Panel;
import com.vaadin.ui.PopupDateField;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Window.Notification;

public class PanelForm extends VerticalLayout {
	/**
	 * 
	 */
	private static final long serialVersionUID = 4480993708266974766L;
	private DatabaseHelper dbHelp = null;
	private ComboBox CompCombo = null;
	private HorizontalLayout TopPanel = null;
	private HorizontalLayout PeriodPanel = null;
	private PopupDateField CalcDateField = null;
	private TreeMap<String,PeriodHelper> PHelps = null;
	private StatisticDataHelper SDHelp = null;
	private TreeMap<String, PopupDateField> PeriodDateControls = null;
	private TreeMap<String, ComboBox> PeriodComboControls = null;
	private Panel MainPanel = null;
	private HorizontalSplitPanel StatPanel = null;
	private Button bRefresh = null;
	private boolean FirstPaintPeriod = false;
	
	public PanelForm (DatabaseHelper dbHelper) throws Exception{
		this.dbHelp = dbHelper;
		TopPanel = new HorizontalLayout();
		CalcDateField = new PopupDateField();
		CalcDateField.setResolution(PopupDateField.RESOLUTION_DAY);
		CalcDateField.setValue(new Date());
		TopPanel.addComponent(CalcDateField);
		bRefresh = new Button(dbHelp.getWords("Refresh"), new Button.ClickListener(){
			/**
			 * 
			 */
			private static final long serialVersionUID = -4710822128273281780L;

			@Override
			public void buttonClick(ClickEvent event) {
				// TODO Auto-generated method stub
				try {
					dbHelp.refreshAll();
					paintPeriods();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}});
		TopPanel.addComponent(bRefresh);
		CompCombo = new ComboBox();
		CompCombo.setImmediate(true);
		CompCombo.setNullSelectionAllowed(false);
		CompCombo.setContainerDataSource(dbHelp.getCompContainer());
		CompCombo.setItemCaptionPropertyId("name");
		TopPanel.addComponent(CompCombo);
		TopPanel.setWidth("100%");
		TopPanel.setComponentAlignment(CalcDateField, Alignment.TOP_LEFT);
		TopPanel.setComponentAlignment(CompCombo, Alignment.TOP_RIGHT);
		this.addComponent(TopPanel);
		PeriodPanel = new HorizontalLayout();
		PeriodPanel.setWidth("100%");
		PeriodPanel.setImmediate(true);
		PHelps = new TreeMap<String,PeriodHelper>(); 
		SDHelp = new StatisticDataHelper(dbHelp);
		PeriodDateControls = new TreeMap<String, PopupDateField>();
		PeriodComboControls = new TreeMap<String, ComboBox>();
 		this.addComponent(PeriodPanel);
 		
 		addCompanyListeners();
 		/////////////////////////
 		MainPanel = new Panel();
 		MainPanel.setWidth("100%");
	}
	
	public void paintPeriods(){
		PeriodPanel.removeAllComponents();
		PeriodDateControls.clear();
		PeriodComboControls.clear();
		FirstPaintPeriod = false;
		SimpleDateFormat df =
			    new SimpleDateFormat("dd.MM.yyyy");
		try{
			for (Object ID:dbHelp.getAPeriodPropsContainer().getItemIds()){
				String PT = new String(dbHelp.getAPeriodPropsContainer().getContainerProperty(ID, "type").getValue().toString());
				PHelps.put(PT,
						new PeriodHelper(dbHelp,ID));
				HorizontalLayout HL = new HorizontalLayout();
				HL.addComponent(new Label(PHelps.get(PT).getPeriod().concat("(").concat(
						dbHelp.getWords(PHelps.get(PT).getCurrent())).concat(")")));
				if (PT.equals("DAILY")) {
					PeriodDateControls.put(PT, new PopupDateField());
					PeriodDateControls.get(PT).setResolution(PopupDateField.RESOLUTION_DAY);
					PeriodDateControls.get(PT).setValue(PHelps.get(PT).getCalculatedDate((Date)CalcDateField.getValue()));
					HL.addComponent(PeriodDateControls.get(PT));
					PeriodDateControls.get(PT).addListener(PeriodChangeListener);
					PeriodDateControls.get(PT).setImmediate(true);
					if (PHelps.get(PT).getCloseDate()!=null){
						Label closelabel = new Label("<b>(".concat(df.format(PHelps.get(PT).getCloseDate())).concat(")</b>"));
						closelabel.setContentMode(Label.CONTENT_XHTML);
						HL.addComponent(closelabel);
						HL.setComponentAlignment(closelabel, Alignment.TOP_LEFT);
					}
				} else {
					PeriodComboControls.put(PT, new ComboBox());
					PeriodComboControls.get(PT).removeAllItems();
					PeriodComboControls.get(PT).setNewItemsAllowed(false);
					PeriodComboControls.get(PT).setNullSelectionAllowed(false);
					PeriodComboControls.get(PT).setRequired(true);
					PeriodComboControls.get(PT).setVisible(true);
					TreeMap<Integer,Period> ComboItems = new TreeMap<Integer,Period>();
					ComboItems = PHelps.get(PT).getLastPeriods(PHelps.get(PT).getCalculatedDate((Date)CalcDateField.getValue()));
					for (int i=PHelps.get(PT).getStatQuant();i>(PHelps.get(PT).getStatQuant()-ComboItems.size());i--){
						PeriodComboControls.get(PT).addItem(ComboItems.get(i).getStartDate());
						if (PHelps.get(PT).getPeriodView())
							PeriodComboControls.get(PT).setItemCaption(ComboItems.get(i).getStartDate(),ComboItems.get(i).getStringValue());
						else PeriodComboControls.get(PT).setItemCaption(ComboItems.get(i).getStartDate(),String.valueOf(ComboItems.get(i).getNumber()));
					}
					HL.addComponent(PeriodComboControls.get(PT));
					PeriodComboControls.get(PT).setValue(ComboItems.get(PHelps.get(PT).getStatQuant()).getStartDate());
					PeriodComboControls.get(PT).addListener(PeriodChangeListener);
					PeriodComboControls.get(PT).setImmediate(true);
					if (PHelps.get(PT).getCloseDate()!=null){
						Label closelabel = new Label("<b>(".concat(df.format(PHelps.get(PT).getCloseDate())).concat(")</b>"));
						closelabel.setContentMode(Label.CONTENT_XHTML);
						HL.addComponent(closelabel);
						HL.setComponentAlignment(closelabel, Alignment.TOP_LEFT);
					}
				}
				PeriodPanel.addComponent(HL);
			}
			FirstPaintPeriod = true;
		} catch (Exception e){
			e.printStackTrace();
			this.getWindow().showNotification(dbHelp.getWords("ServerError"), e.getMessage(), Notification.TYPE_ERROR_MESSAGE);
		}
	}
	
	private void addCompanyListeners(){
		CompCombo.addListener(new Property.ValueChangeListener() {
			/**
			 * 
			 */
			private static final long serialVersionUID = 3553727834189583715L;

			@Override
			public void valueChange(ValueChangeEvent event) {
				// TODO Auto-generated method stub
				Object id = CompCombo.getValue();
				if (!(id instanceof Integer)){
					id = Integer.parseInt(id.toString());
				}
				if (!id.equals(dbHelp.getCompanyId())){
					try	{
					   dbHelp.setCompanyId(id);
					} catch(Exception e) {
			        	AEHelper.logException(e,"Apply button click");
			        	TopPanel.getWindow().showNotification(dbHelp.getWords("ServerError"), e.getMessage(), Notification.TYPE_ERROR_MESSAGE);
					} 
				}
				paintPeriods();
			}
			
		});
		dbHelp.addCompanyListener(new Property.ValueChangeListener() {
			/**
			 * 
			 */
			private static final long serialVersionUID = -4482321290539424815L;

			@Override
			public void valueChange(ValueChangeEvent event) {
				// TODO Auto-generated method stub
				Object id = CompCombo.getValue();	
                if (id!=null && !(id instanceof Integer))
                {
               	 id = Integer.parseInt(id.toString());
                }
                if (id==null || !id.equals(dbHelp.getCompanyId()))
                {
               	 CompCombo.setValue(dbHelp.getCompanyId());
                }
    			paintPeriods();
			}			
		});
	}
	
	private Property.ValueChangeListener PeriodChangeListener = new Property.ValueChangeListener(){
		/**
		 * 
		 */
		private static final long serialVersionUID = -4803173876611686657L;

		@Override
		public void valueChange(ValueChangeEvent event) {
			// TODO Auto-generated method 
		}
		
	};
}
